import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';

// 模拟用户实体类
class User {
  final int id;
  final String name;
  final String email;
  final int age;
  final String department;
  final String city;
  final String country;
  int salary;

  User({
    required this.id,
    required this.name,
    required this.email,
    required this.age,
    required this.department,
    required this.city,
    required this.country,
    required this.salary,
  });

  User copyWith({
    int? id,
    String? name,
    String? email,
    int? age,
    String? department,
    String? city,
    String? country,
    int? salary,
  }) {
    return User(
      id: id ?? this.id,
      name: name ?? this.name,
      email: email ?? this.email,
      age: age ?? this.age,
      department: department ?? this.department,
      city: city ?? this.city,
      country: country ?? this.country,
      salary: salary ?? this.salary,
    );
  }
}

class StreamUserPage extends StatefulWidget {
  const StreamUserPage({super.key});

  @override
  State<StreamUserPage> createState() => _StreamUserPageState();
}

class _StreamUserPageState extends State<StreamUserPage> {
  late StreamController<List<User>> _userStreamController;
  late Stream<List<User>> _userStream;
  Timer? _updateTimer;
  bool _isUpdating = false;
  Random _random = Random();
  
  // 生成5000条模拟用户数据
  List<User> _users = [];
  
  // 部门列表
  final List<String> _departments = [
    '技术部', '产品部', '设计部', '市场部', '运营部', '人事部', '财务部', '客服部'
  ];
  
  // 城市列表
  final List<String> _cities = [
    '北京', '上海', '深圳', '广州', '杭州', '南京', '成都', '武汉', '西安', '厦门'
  ];

  @override
  void initState() {
    super.initState();
    _userStreamController = StreamController<List<User>>();
    _userStream = _userStreamController.stream.asBroadcastStream();
    
    // 生成5000条模拟数据
    _generateSampleData();
    
    // 初始化发送一次数据
    _userStreamController.add(List.from(_users));
  }

  @override
  void dispose() {
    _stopUpdating();
    _userStreamController.close();
    super.dispose();
  }
  
  // 生成5000条示例数据
  void _generateSampleData() {
    _users = List.generate(5000, (index) {
      return User(
        id: index + 1,
        name: '用户${index + 1}',
        email: 'user${index + 1}@example.com',
        age: 20 + _random.nextInt(40), // 年龄20-60
        department: _departments[_random.nextInt(_departments.length)],
        city: _cities[_random.nextInt(_cities.length)],
        country: '中国',
        salary: 5000 + _random.nextInt(20000), // 薪资5000-25000
      );
    });
  }

  // 开始模拟数据更新
  void _startUpdating() {
    if (_updateTimer != null && _updateTimer!.isActive) return;
    
    setState(() {
      _isUpdating = true;
    });
    
    _updateTimer = Timer.periodic(const Duration(milliseconds: 500), (timer) {
      try {
        // 随机更新部分用户数据（每次更新前100条）
        _updateUsersRandomly();
        // 发送更新后的数据
        _userStreamController.add(List.from(_users));
      } catch (e) {
        print('更新用户数据时出错: $e');
      }
    });
    
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('开始模拟数据实时更新，每500ms更新一次用户数据'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }
  
  // 随机更新用户数据
  void _updateUsersRandomly() {
    // 只更新前100条数据以提高性能
    for (int i = 0; i < 100 && i < _users.length; i++) {
      // 随机调整薪资(-1000 到 1000)
      int salaryChange = _random.nextInt(2001) - 1000;
      _users[i] = _users[i].copyWith(
        salary: (_users[i].salary + salaryChange).clamp(3000, 50000),
        age: (_users[i].age + (_random.nextBool() ? 1 : -1)).clamp(18, 65)
      );
    }
  }
  
  // 停止模拟数据更新
  void _stopUpdating() {
    _updateTimer?.cancel();
    _updateTimer = null;
    
    if (mounted) {
      setState(() {
        _isUpdating = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('已停止模拟数据更新'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('实时数据观察'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          // 顶部状态文案区域
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: _isUpdating 
                  ? Colors.green.shade50 
                  : Colors.blue.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: _isUpdating 
                    ? Colors.green.shade200 
                    : Colors.blue.shade200,
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      _isUpdating ? Icons.visibility : Icons.visibility_off,
                      color: _isUpdating ? Colors.green : Colors.blue,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      _isUpdating ? '🔴 实时观察中' : '⚪ 静态观察',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: _isUpdating ? Colors.green.shade700 : Colors.blue.shade700,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  _isUpdating 
                      ? '正在每500ms自动更新用户数据，观察实时变化效果'
                      : '点击右下角播放按钮开始模拟实时数据更新',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey.shade600,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  '数据总量: ${_users.length}条',
                  style: const TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
          // 用户列表内容
          Expanded(child: _body()),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        heroTag: "toggle_update",
        onPressed: _isUpdating ? _stopUpdating : _startUpdating,
        backgroundColor: _isUpdating ? Colors.red : Colors.blue,
        icon: Icon(
          _isUpdating ? Icons.stop : Icons.play_arrow,
          color: Colors.white,
        ),
        label: Text(
          _isUpdating ? '停止更新' : '开始更新',
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget _body() {
    return StreamBuilder<List<User>>(
      stream: _userStream,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }

        if (snapshot.hasError) {
          return Center(
            child: Text('错误: ${snapshot.error}'),
          );
        }

        final users = snapshot.data ?? [];

        if (users.isEmpty) {
          return const Center(
            child: Text(
              '暂无数据',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16),
            ),
          );
        }

        return ListView.builder(
          padding: const EdgeInsets.all(16),
          itemCount: users.length,
          itemBuilder: (context, index) {
            final user = users[index];
            return Card(
              margin: const EdgeInsets.only(bottom: 8),
              child: ListTile(
                leading: CircleAvatar(
                  child: Text(user.id.toString()),
                ),
                title: Text(user.name),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('邮箱: ${user.email}'),
                    Text('年龄: ${user.age} | 部门: ${user.department}'),
                    Text('城市: ${user.city}, ${user.country}'),
                  ],
                ),
                trailing: Text(
                  '\$${user.salary}',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.green,
                  ),
                ),
                isThreeLine: true,
              ),
            );
          },
        );
      },
    );
  }
}